package zhoug.zui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * 只支持纵向滑动的SwipeRefreshLayout
 * 解决包裹在ViewPager等横向滑动组件外面时,和滑动冲突的问题
 * @Author 35574
 * @Date 2021/1/21
 * @Description
 */
public class VerticalSwipeRefreshLayout extends SwipeRefreshLayout {
    private float startY;
    private float startX;
    /**
     * 标记是否是水平拖拽
     * 水平拖拽不拦截事件
     */
    private boolean mHorizontalDragged;
    private final int mTouchSlop;

    public VerticalSwipeRefreshLayout(@NonNull Context context) {
        this(context,null);
    }

    public VerticalSwipeRefreshLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                // 记录手指按下的位置
                startY = ev.getY();
                startX = ev.getX();
                // 初始化标记
                mHorizontalDragged = false;
                break;
            case MotionEvent.ACTION_MOVE:
                // 如果viewPager正在拖拽中，那么不拦截它的事件，直接return false；
                if(mHorizontalDragged) {
                    return false;
                }
                // 获取当前手指位置
                float endY = ev.getY();
                float endX = ev.getX();
                float distanceX = Math.abs(endX - startX);
                float distanceY = Math.abs(endY - startY);
                // 如果X轴位移大于Y轴位移，那么将事件交给viewPager处理。
                if(distanceX > mTouchSlop && distanceX > distanceY) {
                    mHorizontalDragged = true;
                    return false;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // 初始化标记
                mHorizontalDragged = false;
                break;
        }
        // 如果是Y轴位移大于X轴，事件交给swipeRefreshLayout处理。
        return super.onInterceptTouchEvent(ev);
    }




}
